package org.txazo.stat.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.txazo.stat.service.UserService;
import org.txazo.stat.util.HttpUtil;
import org.txazo.stat.util.log.LoggerManager;
import org.txazo.stat.vo.User;

/**
 * 自动登录过滤器
 * 
 * @author Tu XiaoZhou
 * @since 2013-04-13
 * 
 */
public class AutoLoginSessionFilter implements Filter {

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();

		String url = HttpUtil.getRequestURLAndParameters(request);
		if (url != null) {
			LoggerManager.LOGGER_CONSOLE.debug(HttpUtil
					.getRequestURLAndParameters(request));
		}

		String uri = request.getServletPath();
		String skipAuth = (String) request.getParameter("skipAuth");

		if (uri.equals("/login/login") && skipAuth != null
				&& skipAuth.equals("skipAuth")) {
			chain.doFilter(req, resp);
		} else if (uri.equals("/login/logout")) {
			chain.doFilter(req, resp);
		} else {
			User user = (User) session.getAttribute("user");
			if (user == null) {
				String account = null;
				String password = null;

				Cookie[] cookies = request.getCookies();
				if (cookies != null) {
					for (Cookie cookie : cookies) {
						if (cookie.getName().equals("account")) {
							account = cookie.getValue();
						} else if (cookie.getName().equals("password")) {
							password = cookie.getValue();
						}
					}
				}

				if (account != null && password != null) {
					ApplicationContext context = WebApplicationContextUtils
							.getWebApplicationContext(request
									.getServletContext());
					UserService userService = (UserService) context
							.getBean("userService");
					User login = userService.login(account, password);
					if (login != null) {
						session.setAttribute("user", login);
						response.sendRedirect("/login/login?skipAuth=skipAuth");
					} else {
						chain.doFilter(req, resp);
					}
				} else {
					chain.doFilter(req, resp);
				}
			} else {
				chain.doFilter(req, resp);
			}
		}
	}

	@Override
	public void destroy() {
	}

}
